package com.tom.service.impl;

import com.tom.mapper.bwarticle.ArticleMapper;
import com.tom.service.IArticleService;
import com.tom.service.IbatchService;
import com.tom.vo.ArticleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * All rights Reserved, Designed By www.tom.com
 *
 * @version V1.0
 * @Package bw-article-api
 * @Description:
 * @author: dengyi
 * @date: 2020/3/20
 * @Copyright: 2019 www.tomonline-inc.com Inc. All rights reserved.
 * 注意：本内容仅限于TOM集团内部传阅，禁止外泄以及用于其他的商业目
 */
@Slf4j
@Service
public class BatchImpl implements IbatchService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private IArticleService articleService;

    @Override
    public String mandatoryRefresh() {
        log.info("----------强制更新开始");
        StringBuilder failure = new StringBuilder();
        List<ArticleVO> articleList = articleMapper.selectAccessParameters();
        for (ArticleVO article : articleList) {
            log.info("正在更新的文章所有article表的ID为：{}", article.getId());
            Map<String, String> params = new LinkedHashMap<>();
            try {
                for (String param : article.getAccessParameters().split("&")) {
                    String[] keyValue = param.split("=", 2);
                    String key = URLDecoder.decode(keyValue[0], "UTF-8");
                    String value = keyValue.length > 1 ? URLDecoder.decode(keyValue[1], "UTF-8") : "";
                    if (!key.isEmpty()) {
                        params.put(key, value);
                    }
                }
            } catch (UnsupportedEncodingException e) {
                throw new IllegalStateException(e); // Cannot happen with UTF-8 encoding.
            }
            String message = articleService.getArticleContent(article.getLanmu(), params.get("Type"), params.get("ArticleNo"), params.get("SiteNo"), "1",false);
            failure.append(article.getId()).append(message+",");
        }
        return failure.toString();

    }

}
